<?php
declare(strict_types=1);

namespace Service\Consumer\YunCangConsumer\Router;
use App\Amqp\Producer\GoodsGroupProducer;
use App\Model\BbcModel\SyncCount;
use Service\BaseService;
use Service\ConfigureService\ChannelConfigService;
use Service\EsService\EsPublishMsgService;
use Service\PointsService\PointsService;
use Hyperf\Utils\WaitGroup;
use App\Model\BbcModel\GoodsTags;
use App\Model\BbcModel\GoodsSupplyClass;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\ExpressTemplate;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsBatch;
use App\Model\BbcModel\GoodsBrand;
use App\Model\BbcModel\GoodsSpecPrice;
use App\Model\BbcModel\DistributorPrice;
use Service\GoodsService\GoodsSpecPriceService;
use App\Model\BbcModel\MnStoreGoods;
use App\Model\BbcModel\Storage;
use App\Model\BbcModel\YunCangSupplier;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\GoodsAttach;
use Service\GoodsService\GoodsBaseService;
use Service\Code\Normal;
use App\Model\BbcModel\TransitTemplate;
use Service\MonitorService\MonitorService;
use App\Model\BbcModel\GoodsGroup;
use App\Model\BbcModel\GoodsGroupList;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Amqp\Producer;
use Hyperf\Logger\LoggerFactory;
use App\Model\BbcModel\VipConfig;

/**
 * 商品增量更新
 * @author chenshubo
 */
class goodsChange extends BaseService
{
    //映射数据ID
    const map_tag       = 'id';
    const map_class     = 'categoryId';
    const map_brand     = 'brandID';
    const map_template  = 'template_id';
    const map_supplier  = 'supplier_id';
    
    /**
     * 商品数据行
     * @var array
     */
    protected $_goods_item = [];
    protected $time = 0;
    
    /**
     * 接收消费数据
     * @param int $sid
     * @param int $cid
     * @param array $data
     * @param string $messageId
     * @param int $IsFinished
     * 此版本同步，暂时不需要同步给云仓总接收数据
     */
    public function consumer(int $sid,int $cid,array $data,string $messageId,int $IsFinished)
    {
        //处理下架商品
        if($IsFinished==1){
            $this->downBatchGoods($cid);
            return Normal::returnCode(Normal::SUC,"处理结束");
        }
        $this->time             = time();
        
        //这一步一定要进行goodsid 去重复，防止并发数据
        $dataList               = array_column($data,null,'goodsId');
        
        //获取积分配置
        $goods_points_config    = PointsService::instance()->getChannelPointsConfig($cid);
        //获取是否同步覆盖商品名称，商品品牌
        $sync_goods_name=0;
        $sync_brand_name=0;
        $cloudSync=ChannelConfigService::instance()->getConfig(['code'=>'cloud_sync','cid'=>$cid]);
        if($cloudSync['code']==Normal::SUC && !empty($cloudSync['data'])){
            $sync_goods_name=$cloudSync['data']['value']['goods_name']??0;
            $sync_brand_name=$cloudSync['data']['value']['brand_name']??0;
        }
        
        //运费模板
        $template       = TransitTemplate::instance()->info(['cid'=>$cid,'status'=>1,'df'=>0]);
        $template_id    = $template['id'] ?? 0;
        //初始化商品基本属性数据
        $_all_properties_map_list     = $this->__init_commodity_properties($sid, $cid,$data);
        //获取商品服务说明
        $service = GoodsBaseService::instance()->getService($cid);
        
        $_data_extra = [
            'goods_points_config'   => $goods_points_config,
            'sync_goods_name'       => $sync_goods_name,
            'sync_brand_name'       => $sync_brand_name,
            'template'              => $template,
            'properties_data'       => $_all_properties_map_list,
            'goods_service'         => $service,
            'template_id'           => $template_id
        ];
        
        //开始商品协程
        $result_all     = [];
        $successNum     = [];
        $failureNum     = [];
        $count          = count($dataList);
        $channelGoodsCo = new WaitGroup();
        $channelGoodsCo->add($count);
        foreach ($dataList as $goods)
        {
            co(function () use ($channelGoodsCo,$goods,$sid,$cid,$_data_extra,& $result_all,& $successNum,& $failureNum)
            {
                //休眠10ms
                usleep(10000);
                try
                {
                    //开启单个商品消费
                    $result = $this->consumerSingleGoods($sid,$cid,$goods,$_data_extra);
                    if( $result['code'] == Normal::SUC )  {
                        $successNum[] = $result;
                    } else {
                        $failureNum[] = $result;
                    }
                }
                catch (\Throwable $e)
                {
                    $result = Normal::returnCode(Normal::FAIL,$e->getMessage(),[
                        'errorMsg'  => $e->getFile(),
                        'errorLine' => $e->getLine(),
                    ]);
                }
                $result_all[] = $result;
                $channelGoodsCo->done();
            });
        }
        $channelGoodsCo->wait();
        
        if( !empty($failureNum) ) 
        {
            $error = [
                'failureNumCombineResult' => $failureNum,
            ];
            $contents = json_encode($error,JSON_UNESCAPED_UNICODE);
            MonitorService::instance()->sendMsg($contents,'YC_PUSH_BBC_RECEIVE_LIST.goodsChange队列消费异常');
        }
        
        //开始同步云仓商品接收商品数量
        $_success_count = count($successNum);
        if( !empty($messageId) )
        {
            $hasMessage = SyncCount::instance()->where('MessageId',$messageId)->first();
            if(!empty($hasMessage)) 
            {
                SyncCount::instance()->where('id',$hasMessage->id)->increment('count',$_success_count);
                $_notify_count = $_success_count + $hasMessage->count;
            }
            else
            {
                $insert_count_row = [
                    'cd'        => $this->time,
                    'MessageId' => $messageId,
                    'count'     => $_success_count
                ];
                $_notify_count = $_success_count;
                SyncCount::instance()->add($insert_count_row);
            }
            
            //通知云仓同步数量
            $syncData = [];
            $syncData['message_id']  = $messageId;
            $syncData['goods_count'] = $_notify_count;
            $syncData['cid']         = $cid;
            $result = callRpcCommodityServer('syncChannelGoodsCount',$syncData);
            
            //如果同步数据异常就发起通知
            if( $result['code'] != Normal::SUC ) {
                $contents = json_encode($result,JSON_UNESCAPED_UNICODE);
                MonitorService::instance()->sendMsg($contents,'YC_PUSH_BBC_RECEIVE_LIST队列 syncChannelGoodsCount 同步商品数量 异常');                
            }
        }
        return Normal::returnCode(Normal::SUC,"处理结束",$result_all);
    }

    /**
     * 初始化商品基本属性
     * 防止并发写入问题
     * 分类，品牌，标签，模板，供应商，仓库
     * @param int $sid
     * @param int $cid
     * @param array $goodsList
     */
    public function __init_commodity_properties(int $sid,int $cid, array $goodsList)
    {
        $tagList        = [];
        $classList      = [];
        $brandList      = [];
        $templateList   =  [];
        $supplierList   = [];
        foreach ($goodsList as $goods)
        {
            $sku = current($goods['skuList']);
            $skucode = $sku['skucode'];
            
            //商品标签
            if( $goods['tags'] ) {
                foreach ($goods['tags'] as $_tag_item){
                    $tagList[$_tag_item[self::map_tag]] = $_tag_item['name'];
                }
            }
            
            //分类
            $classList[$goods[self::map_class]] = $goods['categoryName'];
            
            //品牌
            $brandList[$goods[self::map_brand]] = $goods['brandName'];
            
            //运费模板
            if( !empty($goods['freight_template']) ) {
                $templateList[$goods['freight_template'][self::map_template]] = $goods['freight_template'];                
            }
            
            $store = current($sku['storeList']);
            unset($store['goods_batch_list']);
            $supplierList[$store[self::map_supplier]] = $store;
        }
        
        //商品标签
        $dataTagMapList         = $this->goodsTagConsumer($sid,$cid,$tagList);
        //商品三级分类
        $dataClassMapList       = $this->goodsClassConsumer($sid,$cid,$classList);
        //运费模板ID
        $templateMapList        = $this->goodsTemplateConsumer($sid,$cid,$templateList);
        //品牌ID
        $brandMapList           = $this->goodsBrandConsumer($sid,$cid,$brandList);
        //供应商
        $supplierMapList        = $this->goodsSupplierConsumer($sid,$cid,$supplierList);
        return [
            'dataTagMapList'    => $dataTagMapList,
            'dataClassMapList'  => $dataClassMapList,
            'templateMapList'   => $templateMapList,
            'brandMapList'      => $brandMapList,
            'supplierMapList'   => $supplierMapList
        ];
    }
    
    /**
     * 处理商品SKU数据
     * @param int $sid
     * @param int $cid
     * @param array $goods
     * @param array $_data_extra
     * @return mixed
     */
    public function consumerSingleGoods(int $sid,int $cid, array $goods,array $_data_extra)
    {
        //初始化基础数据
        $extends = [
            'goodsName'               => $goods['goodsName'],
            'goodsType'               => $goods['goodsType'],
            'medicinal'               => empty($goods['goods_extends_type']) ? 0 : $goods['goods_extends_type'],
            'wechatOnly'              => $goods['isNeedWeiXinPay'] ?? 0,
            'picAuth'                 => $goods['isNeedUploadIDCard'] ?? 0,
            'id_auth'                 => $goods['isNeedIDCard'] ?? 0,
            'isFastDelivery'          => $goods['fastDeliveryType'] ?? 0,
            'isFreePostFee'           => $goods['isFreePostFee'] ?? 1,
            'goodsImg'                => empty($goods['images']) ? [] : $goods['images'],
            'body'                    => empty($goods['description']) ? '' : $goods['description'],
            'origin'                  => empty($goods['countryName']) ? '' : $goods['countryName'],
            'goods_points_config'     => $_data_extra['goods_points_config'],
            'tags'                    => (array)($goods['tags'] ?? []),
            'high_price'              => $goods['conSumptionPrice'] ?? 0,
            'high_tax_rate'           => $goods['conSumptionTaxRate'] ?? 0,
            'is_combine_goods'        => $goods['isCombineSupplierCommodity'] ?? 0,
            'combine_goods_json_body' => $goods['combineGoodsContents'] ?? '',
        ];
        
        $_all_properties_map_list   = $_data_extra['properties_data'];
        $service                    = $_data_extra['goods_service'];
//        $template                   = $_data_extra['template'];
//        $goods_points_config        = $_data_extra['goods_points_config'];
        $sync_goods_name            = $_data_extra['sync_goods_name'];
        $sync_brand_name            = $_data_extra['sync_brand_name'];

        //商品标签
        $dataTagMapList     = (array)$_all_properties_map_list['dataTagMapList'];
        //商品三级分类
        $dataClassMapList   = $_all_properties_map_list['dataClassMapList'];
        //运费模板ID
        $templateMapList    = $_all_properties_map_list['templateMapList'];
        //品牌ID
        $brandMapList       = $_all_properties_map_list['brandMapList'];
        //供应商集合
        $supplierMapList    = $_all_properties_map_list['supplierMapList'];
        //bbc自己的运费模板ID
        $template_id        = $_data_extra['template_id'];
        //上游处理的express_template_id
        $express_template_id    = !empty($goods['freight_template']) ? ($templateMapList[$goods['freight_template']['template_id']] ??0) : 0;
        $class_id               = $dataClassMapList[$goods[self::map_class]]['class_id'];
        $supply_class_id        = $dataClassMapList[$goods[self::map_class]]['supplyClassId'];
        $brand_id               = $brandMapList[$goods[self::map_brand]];
        $supply_tag             = $this->getGoodsTagByLocal($extends['tags'],$dataTagMapList);
        $skuList                = $goods['skuList'];
        $goods_img              = $extends['goodsImg'];
        $sku                    = current($skuList);
        $sku['supplierMapList'] = $supplierMapList;
        $skucode                = $sku['skucode'];
        $buy_limit              = (int)$sku['limit_buy_count'];
        $price_control          = empty($sku['price_control'])?$sku['price']:$sku['price_control'];
        $commodity_customer_info = !empty($sku['commodity_customer_info'])?json_encode($sku['commodity_customer_info'],JSON_UNESCAPED_UNICODE):'';
        $businessLicenseNo      = $sku['storeList'][0]['BusinessLicenseNo']??'';
        $goods_points_config    = $extends['goods_points_config'];
        $img                    = $goods_img[0] ?? '';
        $high_price             = round($extends['high_price']*$sku['tax_rate']+$extends['high_price'],2);
        $old_sku                = Goods::instance()->info(['sid' => $sid,'cid' => $cid,'skucode' => $skucode]);
        //如果是新增数据
        if( empty($old_sku) )
        {
            $_insert_goods = [
                'commodity_customer_info' => $commodity_customer_info,
                'skucode'                 => $sku['skucode'],
                'unit_name'               => empty($goods['unitName'])?'':$goods['unitName'],
                'barcode'                 => $sku['barcode'],
                'is_bonded'               => $extends['goodsType'],
                'name'                    => $extends['goodsName'],
                'status'                  => 0,
                'tag'                     => 0,
                'img'                     => $img,
                'medicinal'               => $extends['medicinal'],
                'wechat_only'             => $extends['wechatOnly'],
                'pic_auth'                => $extends['picAuth'],
                'id_auth'                 => $extends['id_auth'],
                'price'                   => $sku['price'],
                'price_recommend'         => $sku['price'],
                'price_cost'              => $sku['price_cost'],
                'price_vip'               => $sku['price'],
                'price_store'             => $sku['price_cost'],
                'body'                    => $extends['body'],
                'tax_rate'                => $sku['tax_rate'],
                'tax_free'                => $sku['has_rate'],
                'tax_free_cloud'          => $sku['has_rate'],
                'is_high_goods'           => 0,
                'high_price'              => $high_price,
                'high_tax_rate'           => $extends['high_tax_rate'],
                'class_id'                => $class_id,
                'supply_class_id'         => $supply_class_id,
                'brand_id'                => $brand_id,
                'origin'                  => $extends['origin'],
                'is_sync'                 => 1,
                'express_template'        => $express_template_id,
                'isfree_postfee'          => $extends['isFreePostFee'],
                'is_fast_delivery'        => $extends['isFastDelivery'],
                'supply_tag'              => $supply_tag,
                'use_points'              => $goods_points_config['points_auto'],
                'return_points'           => $goods_points_config['return_points_auto'],
                'down_status'             => 1,
                'template_id'             => $template_id,
                'license_no'              => $businessLicenseNo,
                'cid'                     => $cid,
                'sid'                     => $sid,
                'df'                      => 0,
                'cd'                      => $this->time,
                'md'                      => $this->time,
                'is_combine_goods'        => $extends['is_combine_goods'],
                'combine_goods_json_body' => $extends['combine_goods_json_body'],
            ];
            
            if( $extends['medicinal'] > 0 ) {
                $_insert_goods['price_recommend']       = $price_control;
                $_insert_goods['price_recommend_vip']   = $price_control;
                $_insert_goods['price_recommend_svip']  = $price_control;
            }
            else
            {
                $_insert_goods['price_recommend_vip']   = $_insert_goods['price_recommend'];
                $_insert_goods['price_recommend_svip']  = $_insert_goods['price_recommend'];
            }

            //获取商品服务说明
            if( !empty($service) ) {
                $_insert_goods['service_id'] = implode(',',array_column($service,'id'));
            }
            
            //限购
            if( $buy_limit > 0 ) {
                $_insert_goods['buy_limit']     = $buy_limit;
                $_insert_goods['limit_type']    = 2;
            }
            if($_insert_goods['is_bonded']==1 && $sku['has_rate']==0){
                $spec_num=$sku['storeList'][0]['goods_batch_list'][0]['spec_list'][0]['spec_num']??1;
                //下游要求全部显示含税价格，高地税按照含税价格对比，所以从商品从源头全部改成含税
                $_insert_goods['tax_free']=1;
                if($extends['high_price']>0 && $_insert_goods['price_recommend']>round($extends['high_price']*$spec_num,2)){
                    $_insert_goods['price_recommend']=round($_insert_goods['price_recommend']*$_insert_goods['high_tax_rate']+$_insert_goods['price_recommend'],2);
                    $_insert_goods['price_recommend_vip']=round($_insert_goods['price_recommend_vip']*$_insert_goods['high_tax_rate']+$_insert_goods['price_recommend_vip'],2);
                    $_insert_goods['price_recommend_svip']=round($_insert_goods['price_recommend_svip']*$_insert_goods['high_tax_rate']+$_insert_goods['price_recommend_svip'],2);
                }else{
                    $_insert_goods['price_recommend']=round($_insert_goods['price_recommend']*$sku['tax_rate']+$_insert_goods['price_recommend'],2);
                    $_insert_goods['price_recommend_vip']=round($_insert_goods['price_recommend_vip']*$sku['tax_rate']+$_insert_goods['price_recommend_vip'],2);
                    $_insert_goods['price_recommend_svip']=round($_insert_goods['price_recommend_svip']*$sku['tax_rate']+$_insert_goods['price_recommend_svip'],2);
                }

                if($extends['high_price']>0 && $_insert_goods['price_cost']>round($extends['high_price']*$spec_num,2)){
                    $_insert_goods['price_cost']=$_insert_goods['price_store']=round($_insert_goods['price_cost']*$_insert_goods['high_tax_rate']+$_insert_goods['price_cost'],2);
                }else{
                    $_insert_goods['price_cost']=$_insert_goods['price_store']=round($_insert_goods['price_cost']*$sku['tax_rate']+$_insert_goods['price_cost'],2);
                }
                if($extends['high_price']>0 && $_insert_goods['price']>round($extends['high_price']*$spec_num,2)){
                    $_insert_goods['price']=round($_insert_goods['price']*$_insert_goods['high_tax_rate']+$_insert_goods['price'],2);
                    $_insert_goods['price_vip']=round($_insert_goods['price_vip']*$_insert_goods['high_tax_rate']+$_insert_goods['price_vip'],2);
                }else{
                    $_insert_goods['price']=round($_insert_goods['price']*$sku['tax_rate']+$_insert_goods['price'],2);
                    $_insert_goods['price_vip']=round($_insert_goods['price_vip']*$sku['tax_rate']+$_insert_goods['price_vip'],2);
                }


            }
            $goods_id = Goods::instance()->add($_insert_goods);
            $_insert_goods['id'] = $goods_id;
            $this->chooseBatch($sid, $cid, $sku, $_insert_goods, $old_sku, $goods_id, 1);
            if( count($goods_img) > 1 ) 
            {
                unset($goods_img[0]);
                $_insert_attch_imgs = [];
                foreach ($goods_img as $_value)
                {
                    $_insert_attch_imgs[] = [
                        'sid'           => $sid,
                        'common_id'     => $goods_id,
                        'type'          => 1,
                        'url'           => $_value,
                        'md'            => $this->time,
                        'cd'            => $this->time
                    ];
                }
                GoodsAttach::instance()->insert($_insert_attch_imgs);
            }

            //推送商品新增记录用于商品分组处理
            $this->goodsGroupMessageProducer(['sid'=>$sid,'cid'=>$cid,'skucode'=>$sku['skucode'],'is_add'=>1]);
            return Normal::returnCode(Normal::SUC,"新增处理完成,新增sku：{$sku['skucode']}");
        }

        //开始处理更新
        $goods_id       = $old_sku['id'];
        $has_batch      = GoodsBatch::instance()->info(['goods_id' => $goods_id,'type'=>0, 'df' => 0]);
        $specList       = !empty($has_batch['spec_list']) ? json_decode($has_batch['spec_list'],true) : [];
        $baseSpec       = $specList[0]['spec_num'] ?? 1;
        
        //删除当前商品有的所有批次信息(非门店)
        GoodsBatch::instance()->where('goods_id',$goods_id)->where('type',0)->delete();
        //商品扩展类型
        $goods_extends_type = empty($goods['goods_extends_type']) ? 0:$goods['goods_extends_type'];

        //需要更新的最新sku数据
        $_need_change_sku =
            [
                'body'                    => $extends['body'],
                'tax_rate'                => $sku['tax_rate'],
                'weight'                  => $sku['weight'],
                'tax_free'                => $sku['has_rate'],
                'tax_free_cloud'          => $sku['has_rate'],
                'high_price'              => $high_price,
                'high_tax_rate'           => $extends['high_tax_rate'],
                'img'                     => $img,
                'class_id'                => $class_id,
                'supply_class_id'         => $supply_class_id,
                'brand_id'                => $brand_id,
                'name'                    => $extends['goodsName'],
                'medicinal'               => $extends['medicinal'],
                'wechat_only'             => $extends['wechatOnly'],
                'supply_tag'              => $supply_tag,
                'pic_auth'                => $extends['picAuth'],
                'id_auth'                 => $extends['id_auth'],
                'express_template'        => $express_template_id,
//                'template_id'             => $template_id,
                'isfree_postfee'          => $goods['isFreePostFee'],
                'is_fast_delivery'        => $goods['fastDeliveryType'],
                'origin'                  => $extends['origin'],//产地
                'price'                   => $sku['price'] ?? '0.00',//建议零售价
                'price_cost'              => $sku['price_cost'] ?? '0.00',//成本价
                'price_vip'               => $sku['price_vip'] ?? '0.00',//会员价
                'is_bonded'               => $extends['goodsType'],
                'commodity_customer_info' => $commodity_customer_info,
                'is_sync'                 => 1,
                'sync_off'                => 0,
                'unit_name'               => empty($goods['unitName']) ? '' : $goods['unitName'],
                'base_spec'               => $baseSpec,
                'license_no'              => $businessLicenseNo,
                'md'                      => $this->time,
                'is_combine_goods'        => $extends['is_combine_goods'],
                'combine_goods_json_body' => $extends['combine_goods_json_body'],
            ];
        if($sync_goods_name==1){
            unset($_need_change_sku['name']);
        }
        if($sync_brand_name==1){
            unset($_need_change_sku['brand_id']);
            $sku['brandName']=GoodsBrand::instance()->where(['id'=>$old_sku['brand_id']])->value('name');
        }else{
            $sku['brandName']=GoodsBrand::instance()->where(['id'=>$brand_id])->value('name');
        }
        if($sku['has_rate']==0 && $_need_change_sku['is_bonded']==1){
            //不含税的保税商品价格加上税，改成含税
            $_need_change_sku['tax_free']=1;
            if($extends['high_price']>0 && $_need_change_sku['price_cost']>round($extends['high_price']*$baseSpec,2)){
                $_need_change_sku['price_cost']=round($_need_change_sku['price_cost']*$_need_change_sku['high_tax_rate']+$_need_change_sku['price_cost'],2);
            }else{
                $_need_change_sku['price_cost']=round($_need_change_sku['price_cost']*$_need_change_sku['tax_rate']+$_need_change_sku['price_cost'],2);
            }
//            $_need_change_sku['price_cost']=round($_need_change_sku['price_cost']*$_need_change_sku['tax_rate']+$_need_change_sku['price_cost'],2);
            if($extends['high_price']>0 && $price_control>round($extends['high_price']*$baseSpec,2)){
                $price_control=round($price_control*$_need_change_sku['high_tax_rate']+$price_control,2);
            }else{
                $price_control=round($price_control*$_need_change_sku['tax_rate']+$price_control,2);
            }
//            $price_control=round($price_control*$_need_change_sku['tax_rate']+$price_control,2);
        }
        if($_need_change_sku['price_cost']<>$old_sku['price_cost']){
            $_need_change_sku['is_price_cost_change']=1;
        }
        //处理重组最新规格
        $spec = $this->goodsSpecConsumer($sid,$goods_id, $sku);
        $spec_list  = $spec['spec_list'];
        $spec_old   = $spec['spec_old'];

        $is_high_vip = VipConfig::instance()->getVipType($cid);

        //按照商品类型处理对应商品价格问题
        if( $goods_extends_type > 0 ){ //控价，限价商品
            $_need_change_sku = $this->goodsLimitOrControlPrice($old_sku,$_need_change_sku,$price_control);
            $_need_change_sku = $this->getGoodsLimitOrControlSpecPriceList($spec_list, $spec_old, $old_sku, $_need_change_sku,$is_high_vip);
        } else {
            $_need_change_sku = $this->goodsNormalPrice($sku,$old_sku,$_need_change_sku);
            $_need_change_sku = $this->getGoodsNormalSpecPriceList($spec_list,$spec_old,$old_sku,$_need_change_sku,$is_high_vip);
        }
        
        
        //如果当前推送消息商品类型$goods_extends_type发生变化的时候，需要修改店铺商品类型
        //0-全球仓店铺利润额 1-全球仓店铺利润率 2-使用推荐零售价 3-自定义价格 
        //1-限价商品 0-普通商品 2-控价商品
        if( $goods_extends_type == 2 && $old_sku['medicinal'] != 2 ) {
            MnStoreGoods::instance()->where('goods_id',$goods_id)->update(['type'=>2,'md'=>$this->time]);
        }

        //判断限价商品C端售价是否小于推荐价格,判断C端价格是否倒挂(处理供应商，处理批次，处理规格价格)
        $_need_change_sku = $this->chooseBatch($sid, $cid, $sku, $_need_change_sku, $old_sku, $goods_id,0);
        
        //处理云仓快配供应商类型数据
        $_need_change_sku = $this->goodsFastDeliveryConsumer($sid, $cid, $sku, $_need_change_sku, $old_sku, $goods_id,$spec_list);

        //判断当前SKU状态
        if( $sku['status'] == 0 || (isset($_need_change_sku['is_should_del']) && $_need_change_sku['is_should_del'] == 1)) {
            $_need_change_sku['df'] = $sku['status'] == 0 ? 1 : 0;
            EsPublishMsgService::instance()->pushNew([$old_sku['id']],'channel','delete');
            //下架店铺商品
            MnStoreGoods::instance()->where('goods_id',$goods_id)->update(['df'=>1,'md'=>time()]);
            $storeGoodsList = MnStoreGoods::instance()->lists(['goods_id'=>$goods_id,'num'=>0,'_fields_'=>'id']);
            $store_rows_ids = array_column($storeGoodsList,'id');
            if( $store_rows_ids ) {
                EsPublishMsgService::instance()->pushNew($store_rows_ids,'store','delete');
            }
        }else{
            //变更渠道商品索引问题
            $_need_change_sku['df'] = 0;
            $channelInsert[]=[
                'id'                   => $old_sku['id'],
                'goodsId'              => $old_sku['id'],
                'name'                 => $sync_goods_name==1?$old_sku['name']:$extends['goodsName'],
                'classifyID'           => $class_id,
                'brandName'            => $sku['brandName'],
                'channelID'            => $cid,
                'isTrade'              => 0,
                'isChannelGoodsActive' => $old_sku['status']>0
            ];
            EsPublishMsgService::instance()->pushNew($channelInsert,'channel','insert');
            //商品上架状态
            $storeIds = $_need_change_sku['store_ids'];
            if( $old_sku['status'] == 1 && !empty($storeIds) ){
                $storeGoodsList = MnStoreGoods::instance()
                ->select(['id','mn_sid','status'])
                ->where('goods_id',$goods_id)
                ->whereIn('mn_sid',$storeIds)
                ->where('df',1)
                ->get()
                ->toArray();
                $store_change_goods = [];
                foreach ($storeGoodsList as $value){
                    $store_change_goods[] = [
                        'id'                     => $value['id'],
                        'ChannelID'              => $cid,
                        'storeID'                => $value['mn_sid'],
                        'goodsId'                => $goods_id,
                        'name'                   => $sync_goods_name==1?$old_sku['name']:$extends['goodsName'],
                        'classifyID'             => $_need_change_sku['class_id'],
                        'brandName'              => $sku['brandName'],
                        'isTrade'                => 0,
                        'isChannelGoodsActive'   => $old_sku['status']>0,
                        'isStoreGoodsActive'     => $value['status']>0,
                    ];
                }
                if($store_change_goods){
                    EsPublishMsgService::instance()->pushNew($store_change_goods,'store','insert');
                }
                MnStoreGoods::instance()->where('goods_id',$goods_id)->whereIn('mn_sid',$storeIds)->update(['df'=>0]);
            }
            //Q店成本增加，下架Q店倒挂商品
            if( isset($_need_change_sku['price_store']) && $_need_change_sku['price_store'] > $old_sku['price_store'] ) 
            {
                $price_store = $_need_change_sku['price_store'];
                $storeDeleteGoodsList = MnStoreGoods::instance()
                ->where('goods_id',$goods_id)
                ->where('type',3)//自定义价格
                ->where('price_vip','<',$price_store)//价格倒挂
                ->where('status',1)//1-已上架
                ->where('df',0)//未删除
                ->where('num',0)//线下商品线上可用库存数量为0
                ->get()
                ->toArray();
                
                //店铺商品索引删除
                if($storeDeleteGoodsList){
                    $return['storeGoods'] = array_column($storeDeleteGoodsList,'id');
                    EsPublishMsgService::instance()->pushNew($return['storeGoods'],'store','delete');
                    MnStoreGoods::instance()
                    ->where('goods_id',$goods_id)
                    ->where('type',3)
                    ->where('price_vip','<',$price_store)
                    ->where('status',1)
                    ->where('df',0)
                    ->update(['status'=>0]);
                }
            }
        }
        
        //是否限购处理
        if( $buy_limit >0 ) {
            $_need_change_sku['buy_limit']   = $buy_limit;
            $_need_change_sku['limit_type']  = 2;
        }
        
        if( isset($_need_change_sku['store_ids']) ) {
            unset($_need_change_sku['store_ids']);
        }
        
        if( isset($_need_change_sku['is_should_del']) ) {
            unset($_need_change_sku['is_should_del']);
        }
        Goods::instance()->where('id',$goods_id)->update($_need_change_sku);
        if( count($goods_img) > 1)
        {
            unset($goods_img[0]);
            GoodsAttach::instance()->where('sid',$sid)->where('common_id',$goods_id)->where('type',1)->delete();
            $_insert_attch_imgs = [];
            foreach ($goods_img as $_value)
            {
                $_insert_attch_imgs[] = [
                    'sid'           => $sid,
                    'common_id'     => $goods_id,
                    'type'          => 1,
                    'url'           => $_value,
                    'md'            => $this->time,
                    'cd'            => $this->time
                ];
            }
            
            GoodsAttach::instance()->insert($_insert_attch_imgs);
        }
        else
        {
            GoodsAttach::instance()->where('sid',$sid)->where('common_id',$goods_id)->where('type',1)->delete();
        }

        //推送商品变更记录用于商品分组处理
        $this->goodsGroupMessageProducer(['sid'=>$sid,'cid'=>$cid,'skucode'=>$sku['skucode'],'is_add'=>0]);

        return Normal::returnCode(Normal::SUC,"更新处理完成,sku：{$sku['skucode']}");
    }
    
    /**
     * 获取本地已经写好的TAGID
     * @param array $original_tags
     * @param array $new_tags
     */
    public function getGoodsTagByLocal( array $original_tags = [], array $new_tags = [] )
    {
        if( empty($original_tags) ) {
            return false;
        }
        
        $new_tag_ids = [];
        foreach ($original_tags as $item) {
            $new_tag_ids[] = $new_tags[$item['id']];
        }
        return \implode(",",$new_tag_ids);
    }
    
    /**
     * 处理云仓快配供应商类型数据
     * @param int $sid
     * @param int $cid
     * @param array $sku
     * @param array $_need_change_sku
     * @param array $old_sku
     * @param int $goods_id
     * @param array $spec_list
     */
    public function goodsFastDeliveryConsumer(int $sid,int $cid,array $sku,array $_need_change_sku, array $old_sku,int $goods_id, array $spec_list)
    {
        $is_fast_delivery = $_need_change_sku['is_fast_delivery'];
        $high_price = $_need_change_sku['high_price'];
        $is_bonded = $_need_change_sku['is_bonded'];
        $table = MnStoreGoods::instance()->getTable();
        $mn_goods_query = MnStoreGoods::instance()
        ->from("{$table} as lmsg")
        ->select([
            'lmsg.*',
            'lmu.level',
            'lmu.price_limit'
        ])
        ->join('ly_mn_user as lmu','lmu.id','=','lmsg.mn_sid')
        ->where('lmsg.goods_id',$goods_id);
        
        $mn_user_query = Mnuser::instance()
        ->where('check_status',1)
        ->where('is_pay',1)
        ->where('pid',$cid);
        
        //goods_source 1-普通仓 2-前置仓 4-中心仓  其余数字为组合
        if( $is_fast_delivery == 1 ) 
        {
            //商品源
            $goods_source = [2,3,6,7];
            
            //查询店铺商品
            $mn_goods_query->where('lmu.type',3)->where('lmu.supplier_id',$_need_change_sku['supplier_id'])->whereIn('lmu.goods_source',$goods_source);
            
            //查询店铺用户
            $mn_user_query = $mn_user_query->where('type',3)->where('supplier_id',$_need_change_sku['supplier_id'])->whereIn('goods_source',$goods_source);
        }
        elseif ( $is_fast_delivery == 2 )
        {
            //商品源
            $goods_source = [4,5,6,7];
            
            //查询店铺商品
            $mn_goods_query = $mn_goods_query->where(function($query) use ($goods_source)
            {
                $query->orWhere(function($query)
                {
                    $query->whereIn('lmu.type',[1,2]);
                })
                ->orWhere(function($query) use ($goods_source)
                {
                    $query->where('lmu.type',3)->whereIn('lmu.goods_source',$goods_source);
                });
            });            
            
            //查询店铺用户
            $mn_user_query = $mn_user_query
            ->where(function($query) use ($goods_source)
            {
                $query
                ->orWhere(function($query)
                {
                    $query->whereIn('type',[1,2]);
                })
                ->orWhere(function($query) use ($goods_source)
                {
                    $query->where('type',3)->whereIn('goods_source',$goods_source);
                });
            });
        }
        else
        {
            //商品源
            $goods_source = [1,5,3,7];
            
            //查询店铺商品
            $mn_goods_query = $mn_goods_query->where(function($query) use ($goods_source)
            {
                $query
                ->orWhere(function($query)
                {
                    $query->whereIn('lmu.type',[1,2]);
                })
                ->orWhere(function($query) use ($goods_source)
                {
                    $query->where('lmu.type',3)->whereIn('lmu.goods_source',$goods_source);
                });
            });
            
            //查询店铺用户
            $mn_user_query = $mn_user_query
            ->where(function($query) use ($goods_source)
            {
                $query
                ->orWhere(function($query)
                {
                    $query->whereIn('type',[1,2]);
                })
                ->orWhere(function($query) use ($goods_source)
                {
                    $query->where('type',3)->whereIn('goods_source',$goods_source);
                });
            });
        }
        
        $mn_goods_list  = $mn_goods_query->get()->toArray();
        $mn_user_list   = $mn_user_query->get()->toArray();
        if($mn_goods_list) 
        {
            $price_store            = $_need_change_sku['price_store']           ?? $old_sku['price_store'];
            $price_recommend        = $_need_change_sku['price_recommend']       ?? $old_sku['price_recommend'];
            $price_recommend_vip    = $_need_change_sku['price_recommend_vip']   ?? $old_sku['price_recommend_vip'];
            $price_recommend_svip   = $_need_change_sku['price_recommend_svip']  ?? $old_sku['price_recommend_svip'];

            //获取第一个规格
            $newBaseSpec = current($spec_list)['spec_num'];
            
            //处理店铺商品逻辑
            foreach ($mn_goods_list as $item)
            {
                $mn_goods_id = $item['id'];
                $levelPrice = DistributorPrice::instance()->info(['goods_id'=> $goods_id,'level_id'=>$item['level'],'spec_num'=>$newBaseSpec]);
                if(empty($levelPrice))
                {
                    $levelPrice['price'] = $price_store;
                }
                
                //店铺分销商品价格设置类型
                switch ($item['type'])
                {
                    default:
                    case 0://全球仓店铺利润额 
                        $price       = $levelPrice['price']+$item['profit'];
                        $price_vip   = $levelPrice['price']+$item['profit_vip'];
                        $price_svip  = $levelPrice['price']+$item['profit_svip'];
                        break;
                    case 1://全球仓店铺利润率
                        $price       = round($levelPrice['price'] * $item['profit'] / 100+$levelPrice['price'], 2);
                        $price_vip   = round($levelPrice['price'] * $item['profit_vip'] / 100+$levelPrice['price'], 2);
                        $price_svip  = round($levelPrice['price'] * $item['profit_svip'] / 100+$levelPrice['price'], 2);
                        break;
                    case 2://使用推荐零售价
                        $price       = round($price_recommend, 2);
                        $price_vip   = round($price_recommend_vip, 2);
                        $price_svip  = round($price_recommend_svip, 2);
                        break;
                    case 3://自定义价格
                        $price      = $item['price'];
                        $price_vip  = $item['price_vip'];
                        $price_svip  = $item['price_svip'];
                        break;
                }
                
                if( $_need_change_sku['medicinal'] == 1 && ( $price < $price_recommend || $price_vip < $price_recommend_vip) ){
//                    MnStoreGoods::instance()->where('id',$mn_goods_id)->update(['type'=>2,'md'=>$this->time]);
                    $price       = round($price_recommend, 2);
                    $price_vip   = round($price_recommend_vip,2);
                    $price_svip  = round($price_recommend_svip,2);
                    $editStorePrice['type']=2;
                }else{
                    //自定义价格是否倒挂
                    if( $price_vip < $levelPrice['price'] ){
//                        MnStoreGoods::instance()->where('id',$mn_goods_id)->update(['type'=>2,'md'=>$this->time]);
                        $price       = round($price_recommend, 2);
                        $price_vip   = round($price_recommend_vip,2);
                        $price_svip  = round($price_recommend_svip,2);
                        $editStorePrice['type']=2;
                    }
                }
                if( $item['price'] <> round($price/$newBaseSpec,2) || $item['price_vip'] <> round($price_vip/$newBaseSpec,2) || $item['type']==3){
                    $editStorePrice['md']=time();
                    $editStorePrice['is_high_goods']=0;
                    if( $item['price_limit'] == 1 && $item['type'] != 2 && $price_vip<$price_recommend_vip){
                        $editStorePrice['price']=round($price_recommend/$newBaseSpec,2);
                        $editStorePrice['price_vip']=round($price_recommend_vip/$newBaseSpec,2);
                        $editStorePrice['price_svip']=round($price_recommend_svip/$newBaseSpec,2);
                        $editStorePrice['type']=2;
                    }else{
                        $editStorePrice['price']=round($price/$newBaseSpec,2);
                        $editStorePrice['price_vip']=round($price_vip/$newBaseSpec,2);
                        $editStorePrice['price_svip']=round($price_svip/$newBaseSpec,2);
                    }
                    if($is_bonded==1 && $high_price>0 && $editStorePrice['price']>=$high_price){
                        $editStorePrice['is_high_goods']=1;//店铺触发高税率
                    }
                    MnStoreGoods::instance()->where('id',$mn_goods_id)->update($editStorePrice);
                }else{
                    if($is_bonded==1 && $high_price>0 && round($price/$newBaseSpec,2)>=$high_price){
                        MnStoreGoods::instance()->edit(['id'=>$mn_goods_id],['is_high_goods'=>1]);//店铺触发高税率
                    }else{
                        MnStoreGoods::instance()->edit(['id'=>$mn_goods_id],['is_high_goods'=>0]);
                    }
                }
            }
        }
        $_need_change_sku['store_ids'] = array_column($mn_user_list,'id');
        return $_need_change_sku;
    }
    
    /**
     * 处理商品仓库批次选择问题
     * @param int $sid
     * @param int $cid
     * @param array $sku
     * @param array $_need_change_sku
     * @param array $old_sku
     * @param int $goods_id
     * @param int $is_new
     * @return mixed
     */
    public function chooseBatch(int $sid,int $cid,array $sku,array $_need_change_sku, array $old_sku,int $goods_id,int $is_new)
    {
        $supplierMapList = $sku['supplierMapList'];
        unset($sku['supplierMapList']);
        $storageChoose = current($sku['storeList']);
        $storage = Storage::instance()->info(['code'=>$storageChoose['store_code']]);
        $time    = $this->time;
        if( empty($storage) )
        {
            $storage = [
                'code'          => $storageChoose['store_code'],
                'name'          => $storageChoose['store_name'],
                'desc'          => $storageChoose['store_name'],
                'store_type'    => $storageChoose['store_type'],
                'store_mode'    => $storageChoose['store_mode'],
                'cd'            => $time,
                'sid'           => $sid
            ];
            $storage_id = Storage::instance()->add($storage);
            $storage['id'] = $storage_id;
        }
        
        $batch                  = current($storageChoose['goods_batch_list']);
        $storage_num            = (int)$batch['num'];
        $spec_list              = $batch['spec_list'];
        $is_trade               = 0;
        $store_isCombineOrders  = $storageChoose['store_isCombineOrders']??null;
        $supplier_alias         = empty($storageChoose['supplier_alias'])   ? '' : $storageChoose['supplier_alias'];
        $supplier_id            = $storageChoose['supplier_id'];
        //写入批次表数据
        $_insert_goods_batch = [
            'cd'                    => $time,
            'md'                    => $time,
            'num'                   => $storage_num,
            'cid'                   => $cid,
            'sid'                   => $sid,
            'batch_no'              => empty($batch['batch_no'])?'':$batch['batch_no'],
            'make_date'             => isset($batch['spec_list'][0]['make_date'])?strtotime($batch['spec_list'][0]['make_date']):0,
            'expired_date'          => isset($batch['spec_list'][0]['expired_date'])?strtotime($batch['spec_list'][0]['expired_date']):0,
            'storage_code'          => $storageChoose['store_code'],
            'storage_name'          => $storageChoose['store_name'],
            'supplier_id'           => $supplier_id,
            'supplier_name'         => $supplier_alias,
            'store_isCombineOrders' => $store_isCombineOrders?1:0,
            'storage_id'            => $storage['id'],
            'goods_id'              => $goods_id,
            'spec_list'             => json_encode($spec_list,JSON_UNESCAPED_UNICODE),
        ];
        
        Goodsbatch::instance()->add($_insert_goods_batch);
        $_first_spec = current($batch['spec_list']);
        $spec_num    = $_first_spec['spec_num'] > 1 ? $_first_spec['spec_num'] : 1;
        
        $updateData = [];
        $updateData['num_storage']  = $_need_change_sku['num_storage']  = $storage_num;
        $updateData['is_trade']     = $_need_change_sku['is_trade']     = $is_trade;
        $updateData['stoid']        = $_need_change_sku['stoid']        = $storage['id'];
        $updateData['supplier_skucode']          = $_need_change_sku['supplier_skucode']        = $storageChoose['supplier_skucode'];
        $_need_change_sku['base_spec']           = $updateData['base_spec']          = $spec_num;
        $_need_change_sku['supplier_id']         = $updateData['supplier_id']        = $supplierMapList[$supplier_id]['supply_id'];
        $_need_change_sku['supplier_name']       = $updateData['supplier_name']      = $supplier_alias;
        if( $is_new == 0 )  {
            return $_need_change_sku;
        }

        $_insert_spec = [];
        $spec_list=array_values(array_column($spec_list,null,'spec_num'));
        foreach ($spec_list as $sp_value)
        {
            if($_need_change_sku['tax_free_cloud']==0 && $_need_change_sku['is_bonded']==1){
                //不含税的保税商品价格加上税，改成含税
                $checkPriceCost=$sp_value['priceSettlement'];
                $checkPrice=$sp_value['price'];
                $sp_value['priceSettlement']=round($sp_value['priceSettlement']*$_need_change_sku['tax_rate']+$sp_value['priceSettlement'],2);
                if($_need_change_sku['high_price']>0 && $sp_value['priceSettlement']>$_need_change_sku['high_price']*$sp_value['spec_num']){
                    $sp_value['priceSettlement']=round($checkPriceCost*$_need_change_sku['high_tax_rate']+$checkPriceCost,2);
                }
                $sp_value['price']=round($sp_value['price']*$_need_change_sku['tax_rate']+$sp_value['price'],2);
                if($_need_change_sku['high_price']>0 && $sp_value['price']>$_need_change_sku['high_price']*$sp_value['spec_num']){
                    $sp_value['price']=round($checkPrice*$_need_change_sku['high_tax_rate']+$checkPrice,2);
                }
            }
            $_insert_spec[] = [
                'sid'                   => $sid,
                'goods_id'              => $goods_id,
                'spec_num'              => $sp_value['spec_num'],
                'price_recommend'       => $sp_value['price'],
                'price_market'          => !empty($sp_value['priceMarket'])? $sp_value['priceMarket'] : $sp_value['price'],
                'price_recommend_vip'   => $sp_value['price'],
                'price_cost'            => $sp_value['priceSettlement'],
                'price_store'           => $sp_value['priceSettlement'],
                'yc_price_cost'         => $sp_value['priceCost'] ?? 0,
            ];
        }
        
        GoodsSpecPrice::instance()->insert($_insert_spec);
        Goods::instance()->where('id',$goods_id)->update($updateData);
        return $_need_change_sku;
    }
    
    /**
     * 处理消费规格问题
     * @param int $sid
     * @param int $goods_id
     * @param array $sku
     */
    public function goodsSpecConsumer(int $sid,int $goods_id, array $sku)
    {
        //处理规格价格问题
        $spec_list  = $sku['storeList'][0]['goods_batch_list'][0]['spec_list']??[];
        $spec_list  = array_values(array_column($spec_list,null,'spec_num'));
        $spec       = array_column($spec_list,'spec_num');
        $newBaseSpec    = $spec[0];
        $has_spec_list  = GoodsSpecPrice::instance()->lists(['sid'=>$sid,'goods_id'=>$goods_id]);
        
        //开始商品协程
        $spec_old = [];
        $count = count($has_spec_list);
        $channelGoodsCo = new WaitGroup();
        $channelGoodsCo->add($count);
        foreach ($has_spec_list as $spec_key => $spec_value)
        {
            co(function () use ($channelGoodsCo,$goods_id,$spec_key,$spec_value,$spec,& $spec_old)
            {
                $spec_num = $spec_value['spec_num'];
                if(!in_array($spec_num,$spec))
                {
                    GoodsSpecPrice::instance()->where('id',$spec_value['id'])->delete();
                    DistributorPrice::instance()->where('goods_id',$goods_id)->where('spec_num',$spec_num)->delete();
                }
                else
                {
                    $spec_old[$spec_num] = $spec_value;
                }
                $channelGoodsCo->done();
            });
        }
        $channelGoodsCo->wait();
        return [
            'spec_list' => $spec_list,
            'spec_old'  => $spec_old
        ];
    }
    
    /**
     * 处理商品标签
     * @param int $sid
     * @param int $cid
     * @param array $tagList
     */
    public function goodsTagConsumer(int $sid,int $cid,array $tagList)
    {
        if( empty($tagList) ) {
           return '';
        }
        
        //开始商品协程
        $dataMapList = [];
        $count = count($tagList);
        $channelGoodsCo = new WaitGroup();
        $channelGoodsCo->add($count);
        foreach ($tagList as $tag_id => $tag_name)
        {
            co(function () use ($channelGoodsCo,$sid,$cid,$tag_id,$tag_name,& $dataMapList)
            {
                $info = GoodsTags::instance()->info(['cid'=>$cid,'supid'=>$tag_id]);
                if($info){
                    GoodsTags::instance()->edit(['id'=>$info['id']],['name'=>$tag_name,'show_name'=>$tag_name]);
                    $_data_id = $info['id'];
                }else{
                    $_data_id = GoodsTags::instance()->add([
                        'cid'       => $cid,
                        'supid'     => $tag_id,
                        'name'      => $tag_name,
                        'show_name' => $tag_name
                    ]);
                }
                
                $dataMapList[$tag_id] = $_data_id;
                $channelGoodsCo->done();
            });
        }
        
        $channelGoodsCo->wait();
        return $dataMapList;
    }
    
    /**
     * 处理商品分类
     * @param int $sid
     * @param int $cid
     * @param array $classList
     */
    public function goodsClassConsumer(int $sid,int $cid,array $classList)
    {
        $dataMapList = [];
        $count = count($classList);
        $channelGoodsCo = new WaitGroup();
        $channelGoodsCo->add($count);
        foreach ($classList as $categoryId => $categoryName)
        {
            co(function () use ($channelGoodsCo,$sid,$cid,$categoryId,$categoryName,& $dataMapList)
            {
                
                $supplyClass = GoodsSupplyClass::instance()->info(['name'=>$categoryName,'cid'=>$cid]);
                $class       = GoodsClass::instance()->info(['name'=>$categoryName,'df'=>0,'cid'=>$cid]);
                
                //供应商分类
                if(empty($supplyClass))
                {
                    $supplyClassData = [];
                    $supplyClassData['cid']         = $cid;
                    $supplyClassData['sid']         = $sid;
                    $supplyClassData['name']        = $categoryName;
                    $supplyClassData['supply_id']   = $categoryId;
                    if( $class )
                    {
                        $supplyClassData['class_id'] = $class['id'];
                        $class_id   = $class['id'];
                    }
                    else
                    {
                        $class      = GoodsClass::instance()->info(['name'=>'其他','df'=>0,'cid'=>$cid]);
                        $class_id   = $class['id']??0;
                    }
                    $supplyClassId = GoodsSupplyClass::instance()->add($supplyClassData);
                }
                else
                {
                    $supplyClassId = $supplyClass['id'];
                    if( $supplyClass['class_id'] > 0 ) {
                        //如果供应商分类已关联了渠道分类
                        $class_id = $supplyClass['class_id'];
                    }
                    else
                    {
                        if($class)
                        {
                            $class_id = $class['id'];
                        }
                        else
                        {
                            //没查到
                            $class      = GoodsClass::instance()->info(['name'=>'其他','df'=>0,'cid'=>$cid]);
                            $class_id   = $class['id']??0;
                        }
                    }
                }
                $dataMapList[$categoryId] = [
                    'supplyClassId' => $supplyClassId,
                    'class_id'      => $class_id
                ];
                $channelGoodsCo->done();
            });
        }
        
        $channelGoodsCo->wait();
        return $dataMapList;
    }
    
    /**
     * 商品品牌消费
     * @param int $sid
     * @param int $cid
     * @param array $brandList
     */
    public function goodsBrandConsumer(int $sid,int $cid,array $brandList)
    {
        $dataMapList = [];
        $count = count($brandList);
        $channelGoodsCo = new WaitGroup();
        $channelGoodsCo->add($count);
        foreach ($brandList as $brand_id => $brand_name)
        {
            co(function () use ($channelGoodsCo,$sid,$cid,$brand_id,$brand_name,& $dataMapList)
            {
                $brandName = empty($brand_name) ? '其他' : $brand_name;
                $brand     = GoodsBrand::instance()->info(['name'=>$brandName,'cid'=>$cid]);
                if(empty($brand)){
                    $_insert = [];
                    $_insert['name']    = $brandName;
                    $_insert['cd']      = $this->time;
                    $_insert['cid']     = $cid;
                    $_insert['sid']     = $sid;
                    $_data_id = GoodsBrand::instance()->add($_insert);
                }else{
                
                    $_data_id = $brand['id'];
                    if( $brand['df'] == 1 ) {
                        GoodsBrand::instance()->where('id',$_data_id)->update([
                            'df'    => 0,
                        ]);
                    }
                }
                $dataMapList[$brand_id] = $_data_id;
                $channelGoodsCo->done();
            });
        }
        
        $channelGoodsCo->wait();        
        return $dataMapList;
    }

    /**
     * 商品供应商仓库消费
     * @param int $sid
     * @param int $cid
     * @param array $supplierList
     */
    public function goodsSupplierConsumer(int $sid,int $cid,array $supplierList)
    {
        $dataMapList = [];
        $count = count($supplierList);
        $channelGoodsCo = new WaitGroup();
        $channelGoodsCo->add($count);
        foreach ($supplierList as $supplier_id => $supplier)
        {
            co(function () use ($channelGoodsCo,$sid,$cid,$supplier_id,$supplier,& $dataMapList)
            {
                $supplier_alias     = $supplier['supplier_alias'];
                $is_fast_delivery   = $supplier['FastDeliveryType'];
                $supplier_code      = $supplier['supplier_code'];
                //处理云仓供应商问题
                $supply = YunCangSupplier::instance()->info(['cid'=>$cid,'supplier_id'=>$supplier_id]);
                if( empty($supply) )
                {
                    $_data_id = YunCangSupplier::instance()->add([
                        'cid'               => $cid,
                        'supplier_name'     => $supplier_alias,
                        'supplier_code'     => $supplier_code,
                        'supplier_id'       => $supplier_id,
                        'is_fast_delivery'  => $is_fast_delivery,
                    ]);
                }
                else
                {
                    //修改供应商
                    $_data_id = $supply['id'];
                    if( $supplier_alias <> $supply['supplier_name'] || $is_fast_delivery <> $supply['is_fast_delivery'])
                    {
                        YunCangSupplier::instance()->where('id',$_data_id)->update([
                            'supplier_name'     => $supplier_alias,
                            'is_fast_delivery'  => $is_fast_delivery
                        ]);
                    }
                }
                $dataMapList[$supplier_id] = [
                    'supply_id'         => $_data_id,
                    'is_fast_delivery'  => $is_fast_delivery,
                    'supplier_alias'    => $supplier_alias,
                    'supplier_code'     => $supplier_code,
                ];
                $channelGoodsCo->done();
            });
        }
    
        $channelGoodsCo->wait();
        return $dataMapList;
    }
    
    /**
     * 商品运费模板消费
     * @param int $sid
     * @param int $cid
     * @param array $templateList
     */
    public function goodsTemplateConsumer(int $sid,int $cid,array $templateList)
    {
        $dataMapList = [];
        $count = count($templateList);
        $channelGoodsCo = new WaitGroup();
        $channelGoodsCo->add($count);
        foreach ($templateList as $template_id => $freight_template)
        {
            co(function () use ($channelGoodsCo,$sid,$cid,$template_id,$freight_template,& $dataMapList)
            {
                //云仓运费模板
                $express_template   = ExpressTemplate::instance()->info(['template_id'=>$template_id]);
                if($express_template)
                {
                    ExpressTemplate::instance()->where('id',$express_template['id'])->update([
                        'init_weight'       => $freight_template['init_weight'],
                        'init_money'        => $freight_template['init_money'],
                        'increase_weight'   => $freight_template['increase_weight'],
                        'increase_money'    => $freight_template['increase_money']
                    ]);
                    $express_template_id  = $express_template['id'];
                }else{
                    $express_template_id  = ExpressTemplate::instance()->add([
                        'template_id'       => $template_id,
                        'init_weight'       => $freight_template['init_weight'],
                        'init_money'        => $freight_template['init_money'],
                        'increase_weight'   => $freight_template['increase_weight'],
                        'increase_money'    => $freight_template['increase_money']
                    ]);
                }
                
                $dataMapList[$template_id] = $express_template_id;
                $channelGoodsCo->done();
            });
        }
        
        $channelGoodsCo->wait();
        return $dataMapList;
    }
    
    /**
     * 获取控价或者限价商品价格逻辑
     * @param array $old_sku
     * @param array $_need_change_sku
     * @param $price_control
     */
    public function goodsLimitOrControlPrice(array $old_sku,array $_need_change_sku,$price_control)
    {
        //控价限价商品  推荐价格使用云仓同步价格 不可修改
        $_need_change_sku['price_recommend']        = $price_control;
        $_need_change_sku['price_recommend_vip']    = $price_control;
        $_need_change_sku['price_recommend_svip']   = $price_control;
        
        //默认结算价是否根据云仓价格自动修改
        if( $old_sku['price_cost'] == $old_sku['price_store'] ) //默认结算价是否根据云仓价格自动修改
        {
            $_need_change_sku['price_store'] = $_need_change_sku['price_cost'];
            if( $_need_change_sku['price_store'] > $_need_change_sku['price_recommend'])
            {
                //默认结算价是否倒挂
                $_need_change_sku['status']      = 0;
                $_need_change_sku['down_status'] = 2;
                if( $old_sku['status'] == 1 )
                {
                    $_need_change_sku['is_should_del'] = 1;
                }
            }

        }
        else
        {
            if( $old_sku['price_store'] > $_need_change_sku['price_recommend'])
            {
                //默认结算价是否倒挂
                $_need_change_sku['status']         = 0;
                $_need_change_sku['down_status']    = 2;
                if( $old_sku['status'] == 1 ) 
                {
                    $_need_change_sku['is_should_del'] = 1;
                }
            }
        }
        if($_need_change_sku['is_bonded']==1 && $_need_change_sku['high_price']>0 && round($_need_change_sku['price_recommend']/$_need_change_sku['base_spec'],2)>$_need_change_sku['high_price']){
            $_need_change_sku['is_high_goods']=1;
        }
        
        return $_need_change_sku;
    }
    
    /**
     * 获取正常商品模式价格
     * @param array $sku
     * @param array $old_sku
     * @param array $_need_change_sku
     */
    public function goodsNormalPrice(array $sku,array $old_sku,array $_need_change_sku)
    {
        //是否需要删除标识
        $is_should_del = 0;
        //新数据里面的成本价
        $price_cost =$sku['price_cost'];
        $newBaseSpec=$_need_change_sku['base_spec'];
        $high_price=$_need_change_sku['high_price'];
        if($sku['has_rate']==0 && $_need_change_sku['is_bonded']==1){
            //不含税的保税商品价格加上税，改成含税
            $price_cost=round($price_cost*$_need_change_sku['tax_rate']+$price_cost,2);
            if($_need_change_sku['high_price']>0 && $price_cost>round($_need_change_sku['high_price']*$newBaseSpec,2)){
                $price_cost=round($sku['price_cost']*$_need_change_sku['high_tax_rate']+$sku['price_cost'],2);
            }
        }
        //普通商品
        if( ($old_sku['is_update'] == 1 || $old_sku['is_update_price_recommend'] == 1 ||
                $old_sku['is_update_price_recommend_vip'] == 1 || $old_sku['is_update_price_recommend_svip'] == 1 ||
                $old_sku['is_update_price_market'] == 1) &&
            bccomp((string)$price_cost,(string)$old_sku['price_cost'],2) != 0 && in_array($old_sku['type'],[0,1]) )
        {
            //利润额
            if( $old_sku['type'] == 0 )
            {
                //结算价自动更新
                if( $old_sku['is_update'] == 1)
                {
                    $_need_change_sku['price_store']          = bcadd((string)$price_cost,(string)$old_sku['profit'],2);
                }

                //推荐零售价自动更新
                if ( $old_sku['is_update_price_recommend'] == 1)
                {
                    $_need_change_sku['price_recommend']      = bcadd((string)$price_cost,(string)$old_sku['profit_price'],2);
                }

                //推荐会员价自动更新
                if( $old_sku['is_update_price_recommend_vip'])
                {
                    $_need_change_sku['price_recommend_vip']  = bcadd((string)$price_cost,(string)$old_sku['profit_vip'],2);
                }

                //推荐高级会员价自动更新
                if( $old_sku['is_update_price_recommend_svip'] == 1)
                {
                    $_need_change_sku['price_recommend_svip'] = bcadd((string)$price_cost,(string)$old_sku['profit_svip'],2);
                }

                //市场价自动更新
                if( $old_sku['is_update_price_market'] == 1)
                {
                    $_need_change_sku['price_market'] = bcadd((string)$price_cost,(string)$old_sku['profit_market'],2);
                }
            }
            else
            {
                if( $old_sku['is_update'] == 1)
                {
                    $_need_change_sku['price_store']            = bcadd((string)($old_sku['profit']*$price_cost/100),(string)$price_cost,2);
                }

                if( $old_sku['is_update_price_recommend'])
                {
                    $_need_change_sku['price_recommend']        = bcadd((string)($old_sku['profit_price']*$price_cost/100),(string)$price_cost,2);
                }

                if( $old_sku['is_update_price_recommend_vip'] == 1)
                {
                    $_need_change_sku['price_recommend_vip']    = bcadd((string)($old_sku['profit_vip']*$price_cost/100),(string)$price_cost,2);
                }

                if ( $old_sku['is_update_price_recommend_svip'])
                {
                    $_need_change_sku['price_recommend_svip']   = bcadd((string)($old_sku['profit_svip']*$price_cost/100),(string)$price_cost,2);
                }

                if ( $old_sku['is_update_price_market'])
                {
                    $_need_change_sku['price_market']   = bcadd((string)($old_sku['profit_market']*$price_cost/100),(string)$price_cost,2);
                }
            }
            if($_need_change_sku['is_bonded']==1 && $high_price>0 && (round($_need_change_sku['price_recommend']/$newBaseSpec,2)>=$high_price || round($_need_change_sku['price_recommend_vip']/$newBaseSpec,2)>=$high_price || round($_need_change_sku['price_store']/$newBaseSpec,2)>=$high_price)){
                $_need_change_sku['is_high_goods']=1;//触发高税率
            }
        }
        else
        {
            //价格倒挂的情况下
            if( bccomp((string)$old_sku['price_store'], (string)$price_cost,2) == '-1' )
            {
                $_need_change_sku['status'] = 0;
                $_need_change_sku['down_status'] = 2;
                if( $old_sku['status'] == 1 ) {
                    $is_should_del = 1;
                }
            }

            if($_need_change_sku['is_bonded']==1 && $high_price>0 && (round($old_sku['price_recommend']/$newBaseSpec,2)>=$high_price || round($old_sku['price_recommend_vip']/$newBaseSpec,2)>=$high_price || round($old_sku['price_store']/$newBaseSpec,2)>=$high_price)){
                $_need_change_sku['is_high_goods']=1;//触发高税率
            }
        }
        
        $_need_change_sku['is_should_del'] = $is_should_del;
        return $_need_change_sku;
    }
    
    /**
     * 处理限价控价规格价格问题
     * @param array $new_spec_list
     * @param array $old_spec_list
     * @param array $old_sku
     * @param array $_need_change_sku
     * @param string $is_high_vip
     */
    public function getGoodsLimitOrControlSpecPriceList(array $new_spec_list,array $old_spec_list,array $old_sku,array $_need_change_sku,$is_high_vip)
    {
        foreach ($new_spec_list as $spec_new){
            $spec_edit=[];
            $spec_edit['sid']=$old_sku['sid'];
            $checkPriceCost=$spec_new['priceSettlement'];
            $checkPriceControl=$spec_new['priceControl'];
            if($_need_change_sku['is_bonded']==1 && $_need_change_sku['tax_free_cloud']==0){
                //不含税的保税商品价格加上税，改成含税
                $spec_new['priceSettlement']=round($spec_new['priceSettlement']*$_need_change_sku['tax_rate']+$spec_new['priceSettlement'],2);
                if($_need_change_sku['high_price']>0 && $spec_new['priceSettlement']>round($_need_change_sku['high_price']*$spec_new['spec_num'],2)){
                    $spec_new['priceSettlement']=round($checkPriceCost*$_need_change_sku['high_tax_rate']+$checkPriceCost,2);
                }
                $spec_new['priceControl']=round($spec_new['priceControl']*$_need_change_sku['tax_rate']+$spec_new['priceControl'],2);
                if($_need_change_sku['high_price']>0 && $spec_new['priceControl']>round($_need_change_sku['high_price']*$spec_new['spec_num'],2)){
                    $spec_new['priceControl']=round($checkPriceControl*$_need_change_sku['high_tax_rate']+$checkPriceControl,2);
                }
            }
            if($_need_change_sku['is_bonded']==1 && $_need_change_sku['high_price']>0 && round($spec_new['priceControl']/$_need_change_sku['base_spec'],2)>$_need_change_sku['high_price']){
                $_need_change_sku['is_high_goods']=1;//触发高税率
            }

            $spec_edit['price_recommend']      = $spec_new['priceControl'];
            $spec_edit['price_recommend_vip']  = $spec_new['priceControl'];
            $spec_edit['price_recommend_svip'] = $spec_new['priceControl'];
            $spec_edit['price_market']         = $spec_new['priceMarket'];
            $spec_edit['price_store']          = $spec_new['priceSettlement'];
            $spec_edit['price_cost']           = $spec_new['priceSettlement'];
            $spec_edit['yc_price_cost']        = $spec_new['priceCost'] ?? 0;
//            $spec_edit['price_store']           = $spec_new['priceSettlement'];
//            $spec_edit['price_market']          = $spec_new['priceMarket'];

            if( $old_spec_list && isset($old_spec_list[$spec_new['spec_num']]) ){
                $old    = $old_spec_list[$spec_new['spec_num']];
                if( $old['price_cost'] == $old['price_store']){
//                    $spec_edit['price_store']   = $spec_new['priceSettlement'];
                    //默认结算价是否倒挂
                    if( $spec_edit['price_store'] > $spec_edit['price_recommend']){
                        $_need_change_sku['status']         = 0;
                        $_need_change_sku['down_status']    = 2;
                        if( $old_sku['status'] == 1 ){
                            $_need_change_sku['is_should_del'] = 1;
                        }
                    }

                }else{
//                    $spec_edit['price_store']   = $old['price_store'];
                    //默认结算价是否倒挂
                    if( $old['price_store'] > $spec_edit['price_recommend']){
                        $_need_change_sku['status']         = 0;
                        $_need_change_sku['down_status']    = 2;
                        if( $old_sku['status'] == 1 ){
                            $_need_change_sku['is_should_del'] = 1;
                        }
                    }
                }
                GoodsSpecPrice::instance()->where('id',$old['id'])->update($spec_edit);
            }else{
                $spec_edit['price_store']   = $spec_new['priceSettlement'];
                $spec_edit['goods_id']      = $old_sku['id'];
                $spec_edit['spec_num']      = $spec_new['spec_num'];
                GoodsSpecPrice::instance()->add($spec_edit);
            }
            //查询预估利润是否为负
            if($_need_change_sku['is_bonded']==1 && $_need_change_sku['high_price']>0){
                $pricestoretax_rate=$_need_change_sku['tax_rate'];
                $pricecosttax_rate=$_need_change_sku['tax_rate'];
                if(round($spec_edit['price_store']/$spec_new['spec_num'],2)>=$_need_change_sku['high_price']){
                    $pricestoretax_rate=$_need_change_sku['high_tax_rate'];
                }
                if(round($spec_edit['price_cost']/$spec_new['spec_num'],2)>=$_need_change_sku['high_price']){
                    $pricecosttax_rate=$_need_change_sku['high_tax_rate'];;
                }
                $except_money=round(($spec_edit['price_store']/(1+$pricestoretax_rate)-$spec_edit['price_cost']/(1+$pricecosttax_rate)),2);
                if($except_money<0){
                    $_need_change_sku['status']=0;
                    $_need_change_sku['down_status']=2;
                    if($old_sku['status']==1){
                        $_need_change_sku['is_should_del'] = 1;
                    }
                }
            }

            $max_distributor_price = DistributorPrice::instance()
                ->where(['goods_id' => $old_sku['id']])
                ->where(['spec_num' => $spec_new['spec_num']])
                ->max('price');
            if($spec_edit['price_store'] > $max_distributor_price)
            {
                $max_distributor_price = $spec_edit['price_store'];
            }

            //分销商结算价小于成本价
            $min_distributor_price = DistributorPrice::instance()
                ->where(['goods_id' => $old_sku['id']])
                ->where(['spec_num' => $spec_new['spec_num']])
                ->min('price');
            if($spec_edit['price_store'] < $min_distributor_price) //默认结算价小于分销商结算价
            {
                $min_distributor_price = $spec_edit['price_store'];
            }
            if($max_distributor_price > 0 && $min_distributor_price > 0 && $min_distributor_price < $spec_edit['price_cost'])
            {
                $_need_change_sku['status']         = 0;
                $_need_change_sku['down_status']    = 2;
                if( $old_sku['status'] == 1 ){
                    $_need_change_sku['is_should_del'] = 1;
                }
            }

            //会员价小于分销商结算价
            if(!isset($spec_edit['price_recommend_vip']))
            {
                $price_recommend_vip = $old_sku['price_recommend_vip'];
            }
            else
            {
                $price_recommend_vip = $spec_edit['price_recommend_vip'];
            }
            if( $price_recommend_vip > 0 && $price_recommend_vip < $max_distributor_price)
            {
                $_need_change_sku['status']         = 0;
                $_need_change_sku['down_status']    = 2;
                if( $old_sku['status'] == 1 ){
                    $_need_change_sku['is_should_del'] = 1;
                }
            }

            //高级会员价小于分销商结算价
            if(!isset($spec_edit['price_recommend_svip']))
            {
                $price_recommend_svip = $old_sku['price_recommend_svip'];
            }
            else
            {
                $price_recommend_svip = $spec_edit['price_recommend_svip'];
            }
            if($is_high_vip == 1 && $price_recommend_svip > 0 && $max_distributor_price > 0 && $price_recommend_svip < $max_distributor_price)
            {
                $_need_change_sku['status']         = 0;
                $_need_change_sku['down_status']    = 2;
                if( $old_sku['status'] == 1 ){
                    $_need_change_sku['is_should_del'] = 1;
                }
            }

            //结算价自动更新
            if( isset($old['price_cost']) && $old['price_store'] < $spec_edit['price_cost'])
            {
                $_need_change_sku['status']         = 0;
                $_need_change_sku['down_status']    = 2;
                if( $old_sku['status'] == 1 ){
                    $_need_change_sku['is_should_del'] = 1;
                }
            }
        }
        
        return $_need_change_sku;
    }    
    
    /**
     * 处理获取普通商品规格价格问题
     * @param array $new_spec_list
     * @param array $old_spec_list
     * @param array $old_sku
     * @param array $_need_change_sku
     * @param string $is_high_vip
     */
    public function getGoodsNormalSpecPriceList(array $new_spec_list,array $spec_old,array $old_sku,array $_need_change_sku,$is_high_vip)
    {
        //处理规格问题
        $is_bonded=$_need_change_sku['is_bonded'];
        $high_price=$_need_change_sku['high_price'];
        $baseSpec=$_need_change_sku['base_spec'];

        foreach ($new_spec_list as $spec_new)
        {
            $spec_edit = [];
            $spec_edit['sid'] = $old_sku['sid'];
            $checkPriceCost=$spec_new['priceSettlement'];
            if($_need_change_sku['tax_free_cloud']==0 && $is_bonded==1){
                //不含税的保税商品价格加上税，改成含税
                $spec_new['priceSettlement']=round($spec_new['priceSettlement']*$_need_change_sku['tax_rate']+$spec_new['priceSettlement'],2);
                if($_need_change_sku['high_price']>0 && $spec_new['priceSettlement']>round($_need_change_sku['high_price']*$spec_new['spec_num'],2)){
                    $spec_new['priceSettlement']=round($checkPriceCost*$_need_change_sku['high_tax_rate']+$checkPriceCost,2);
                }
            }
            if( $spec_old && isset($spec_old[$spec_new['spec_num']])){
                //旧的规格组价格
                $old = $spec_old[$spec_new['spec_num']];
                $spec_edit['price_cost']    = $spec_new['priceSettlement'];
                $spec_edit['price_store']   = $old['price_store'];
                $spec_edit['yc_price_cost'] = $spec_new['priceCost'] ?? 0;
                $spec_edit['price_recommend_vip'] = $old['price_recommend_vip'];
                $spec_edit['price_recommend_svip'] = $old['price_recommend_svip'];
//                $spec_edit['price_market']  = $spec_new['priceMarket'];
                $price_cost = $spec_edit['price_cost'];
                if( ($old_sku['is_update'] == 1 || $old_sku['is_update_price_recommend'] == 1 || $old_sku['is_update_price_recommend_vip'] ||
                        $old_sku['is_update_price_recommend_svip'] == 1 || $old_sku['is_update_price_market']) &&
                    $old_sku['price_cost'] <> $price_cost && in_array($old_sku['type'],[0,1]) ){
                    if( $old_sku['type'] == GoodsSpecPriceService::TYPE_PRICE_MONEY ){

                        //结算价自动更新
                        if( $old_sku['is_update'] == 1)
                        {
                            $spec_edit['price_store']           = bcadd((string)$spec_edit['price_cost'],$old_sku['profit'],2);
                        }

                        //推荐零售价自动更新
                        if( $old_sku['is_update_price_recommend'] == 1)
                        {
                            $spec_edit['price_recommend']       = bcadd((string)$spec_edit['price_cost'],$old_sku['profit_price'],2);
                        }

                        //推荐会员价自动更新
                        if ($old_sku['is_update_price_recommend_vip'] == 1)
                        {
                            $spec_edit['price_recommend_vip']   = bcadd((string)$spec_edit['price_cost'],$old_sku['profit_vip'],2);
                        }

                        //推荐高级会员价自动更新
                        if ( $old_sku['is_update_price_recommend_svip'] == 1)
                        {
                            $spec_edit['price_recommend_svip']  = bcadd((string)$spec_edit['price_cost'],$old_sku['profit_svip'],2);

                        }

                        //市场价自动更新
                        if ( $old_sku['is_update_price_market'] == 1)
                        {
                            $spec_edit['price_market']  = bcadd((string)$spec_edit['price_cost'],$old_sku['profit_market'],2);
                        }
                    }else{

                        if ($old_sku['is_update'] == 1)
                        {
                            $spec_edit['price_store']           = bcadd((string)($old_sku['profit']*$spec_edit['price_cost']/100),(string)$spec_edit['price_cost'],2);
                        }

                        if ($old_sku['is_update_price_recommend'])
                        {
                            $spec_edit['price_recommend']       = bcadd((string)($old_sku['profit_price']*$spec_edit['price_cost']/100),(string)$spec_edit['price_cost'],2);
                        }

                        if ($old_sku['is_update_price_recommend_vip'])
                        {
                            $spec_edit['price_recommend_vip']   = bcadd((string)($old_sku['profit_vip']*$spec_edit['price_cost']/100),(string)$spec_edit['price_cost'],2);
                        }

                        if ($old_sku['is_update_price_recommend_svip'])
                        {
                            $spec_edit['price_recommend_svip']  = bcadd((string)($old_sku['profit_svip']*$spec_edit['price_cost']/100),(string)$spec_edit['price_cost'],2);
                        }

                        if ($old_sku['is_update_price_market'])
                        {
                            $spec_edit['price_market']  = bcadd((string)($old_sku['profit_market']*$spec_edit['price_cost']/100),(string)$spec_edit['price_cost'],2);
                        }
                    }
                    if($is_bonded==1 && $high_price>0 && (round($spec_edit['price_recommend']/$spec_new['spec_num'],2)>=$high_price || round($spec_edit['price_store']/$spec_new['spec_num'],2)>=$high_price)){
                        $_need_change_sku['is_high_goods']=1;//触发高税率
                    }
                }else{
                    if( $old['price_store'] < $spec_edit['price_cost']){
                        $_need_change_sku['status']         = 0;
                        $_need_change_sku['down_status']    = 2;
                        if( $old_sku['status'] == 1 ){
                            $_need_change_sku['is_should_del'] = 1;
                        }
                    }
                    if($is_bonded==1 && $high_price>0 && (round($old['price_recommend']/$spec_new['spec_num'],2)>=$high_price || round($old['price_store']/$spec_new['spec_num'],2)>=$high_price)){
                        $_need_change_sku['is_high_goods']=1;//触发高税率
                    }
                }

                if( $old['price_cost'] <> $spec_edit['price_cost'] || $old['yc_price_cost'] <> $spec_edit['yc_price_cost']){
                    GoodsSpecPrice::instance()->where('id',$old['id'])->update($spec_edit);
                }
            }
            else
            {
                $spec_edit['price_cost']    = $spec_new['priceSettlement'];
                $spec_edit['goods_id']      = $old_sku['id'];
                $spec_edit['spec_num']      = $spec_new['spec_num'];
                $spec_edit['yc_price_cost'] = $spec_new['priceCost'] ?? 0;
//                $spec_edit['price_market']  = $spec_new['priceMarket'];
                if( $old_sku['type'] == GoodsSpecPriceService::TYPE_PRICE_MONEY ) //利润额
                {
                    $spec_edit['price_store']           = $spec_edit['price_cost']+$old_sku['profit'];
                    $spec_edit['price_recommend']       = $spec_edit['price_cost']+$old_sku['profit_price'];
                    $spec_edit['price_recommend_vip']   = $spec_edit['price_cost']+$old_sku['profit_vip'];
                    $spec_edit['price_recommend_svip']  = $spec_edit['price_cost']+$old_sku['profit_svip'];
                }
                elseif( $old_sku['type'] == GoodsSpecPriceService::TYPE_PRICE_RATE ) //利润率
                {
                    $spec_edit['price_store']           = $old_sku['profit']*$spec_edit['price_cost']/100+$spec_edit['price_cost'];
                    $spec_edit['price_recommend']       = $old_sku['profit_price']*$spec_edit['price_cost']/100+$spec_edit['price_cost'];
                    $spec_edit['price_recommend_vip']   = $old_sku['profit_vip']*$spec_edit['price_cost']/100+$spec_edit['price_cost'];
                    $spec_edit['price_recommend_svip']  = $old_sku['profit_svip']*$spec_edit['price_cost']/100+$spec_edit['price_cost'];
                }
                else//导入价格
                {
                    $spec_edit['price_store']           = $old_sku['price_store']/$baseSpec*$spec_new['spec_num'];
                    $spec_edit['price_recommend']       = $old_sku['price_recommend']/$baseSpec*$spec_new['spec_num'];
                    $spec_edit['price_recommend_vip']   = $old_sku['price_recommend_vip']/$baseSpec*$spec_new['spec_num'];
                    $spec_edit['price_recommend_svip']  = $old_sku['price_recommend_svip']/$baseSpec*$spec_new['spec_num'];
                }
                GoodsSpecPrice::instance()->add($spec_edit);
                if($is_bonded==1 && $high_price>0 && (round($spec_edit['price_recommend']/$spec_new['spec_num'],2)>=$high_price || round($spec_edit['price_store']/$spec_new['spec_num'],2)>=$high_price)){
                    $_need_change_sku['is_high_goods']=1;//触发高税率
                }
            }
            //查询预估利润是否为负
            if($is_bonded==1 && $high_price>0){
                $pricestoretax_rate=$_need_change_sku['tax_rate'];
                $pricecosttax_rate=$_need_change_sku['tax_rate'];
                if(round($spec_edit['price_store']/$spec_new['spec_num'],2)>=$high_price){
                    $pricestoretax_rate=$_need_change_sku['high_tax_rate'];
                }
                if(round($spec_edit['price_cost']/$spec_new['spec_num'],2)>=$high_price){
                    $pricecosttax_rate=$_need_change_sku['high_tax_rate'];
                }
                $except_money=round(($spec_edit['price_store']/(1+$pricestoretax_rate)-$spec_edit['price_cost']/(1+$pricecosttax_rate)),2);
                if($except_money<0){
                    $_need_change_sku['status']=0;
                    $_need_change_sku['down_status']=2;
                    if($old_sku['status']==1){
                        $_need_change_sku['is_should_del'] = 1;
                    }
                }
            }

            $max_distributor_price = DistributorPrice::instance()
                ->where(['goods_id' => $old_sku['id']])
                ->where(['spec_num' => $spec_new['spec_num']])
                ->max('price');
            if($spec_edit['price_store'] > $max_distributor_price) //默认结算价大于分销商结算价
            {
                $max_distributor_price = $spec_edit['price_store'];
            }

            //分销商结算价小于成本价
            $min_distributor_price = DistributorPrice::instance()
                ->where(['goods_id' => $old_sku['id']])
                ->where(['spec_num' => $spec_new['spec_num']])
                ->min('price');
            if($spec_edit['price_store'] < $min_distributor_price) //默认结算价小于分销商结算价
            {
                $min_distributor_price = $spec_edit['price_store'];
            }
            if($max_distributor_price > 0 && $min_distributor_price > 0 && $min_distributor_price < $spec_edit['price_cost'])
            {
                $_need_change_sku['status']         = 0;
                $_need_change_sku['down_status']    = 2;
                if( $old_sku['status'] == 1 ){
                    $_need_change_sku['is_should_del'] = 1;
                }
            }

            //会员价小于分销商结算价
            if(!isset($spec_edit['price_recommend_vip']))
            {
                $price_recommend_vip = $old_sku['price_recommend_vip'];
            }
            else
            {
                $price_recommend_vip = $spec_edit['price_recommend_vip'];
            }

            if( $price_recommend_vip > 0 && $price_recommend_vip < $max_distributor_price)
            {
                $_need_change_sku['status']         = 0;
                $_need_change_sku['down_status']    = 2;
                if( $old_sku['status'] == 1 ){
                    $_need_change_sku['is_should_del'] = 1;
                }
            }

            //高级会员价小于分销商结算价
            if(!isset($spec_edit['price_recommend_svip'])) //高级会员价不自动更新
            {
                $price_recommend_svip = $old_sku['price_recommend_svip'];
            }
            else
            {
                $price_recommend_svip = $spec_edit['price_recommend_svip'];
            }
            if($is_high_vip == 1 && $price_recommend_svip > 0 && $max_distributor_price > 0 && $price_recommend_svip < $max_distributor_price)
            {
                $_need_change_sku['status']         = 0;
                $_need_change_sku['down_status']    = 2;
                if( $old_sku['status'] == 1 ){
                    $_need_change_sku['is_should_del'] = 1;
                }
            }

            //结算价自动更新
            if($old_sku['is_update'] == 1)
            {
                if($spec_edit['price_store'] < $spec_edit['price_cost'])
                {
                    $_need_change_sku['status']         = 0;
                    $_need_change_sku['down_status']    = 2;
                    if( $old_sku['status'] == 1 ){
                        $_need_change_sku['is_should_del'] = 1;
                    }
                }
            }
            else
            {
                if( isset($old['price_store']) && $old['price_store'] < $spec_edit['price_cost'])
                {
                    $_need_change_sku['status']         = 0;
                    $_need_change_sku['down_status']    = 2;
                    if( $old_sku['status'] == 1 ){
                        $_need_change_sku['is_should_del'] = 1;
                    }
                }
            }
        }
        
        return $_need_change_sku;
    }

    public function goodsGroup_old($sid,$cid){

        /*只同步商品分类*/
        $goods_group_ids = GoodsGroup::instance()
            ->where(['sid'=>$sid,'cid'=>$cid,'is_sync_goods'=>1])
            ->where('goods_range',3)
            ->select(['id','class_ids'])
            ->get()->toArray();
        if(!$goods_group_ids){
            return true;
        }
        $class_ids = array_column($goods_group_ids,'class_ids');
        $class_children_ids = GoodsClass::instance()
            ->where(['sid'=>$sid,'cid'=>$cid,'df'=>0])
            ->whereIn('pid',$class_ids)
            ->pluck('id')->toArray();

//        $all_class = array_unique(array_merge($class_ids,$class_children_ids));
        $goods_ids = Goods::instance()
            ->where(['sid'=>$sid,'cid'=>$cid])
//            ->whereIn('class_id',$all_class)
            ->select(['id','class_id','df'])
            ->get()->toArray();
        $goods_df_group = getArrayGroupData($goods_ids,'df');
        foreach ($goods_group_ids as $key=>$val){
            if(empty($val['class_ids'])){
                continue;
            }
            $class_ids = explode(',',$val['class_ids']);
            $class_id = GoodsClass::instance()
                ->where(['cid'=>$cid,'df'=>0])
                ->whereIn('pid',$class_ids)
                ->pluck('id');
            if($class_id){
                $class_id = $class_id->toArray();
            }
            $class_ids = array_merge($class_ids,$class_id);

            $del_goods_group = $goods_df_group[1] ?? [];
            $del_goods_ids = [];//分类下删除的商品
            foreach ($del_goods_group as $v){
                if(in_array($v['class_id'],$class_ids)){
                    $del_goods_ids[] = $v['id'];
                }
            }
            if($del_goods_ids){
                $page_goods_ids = array_chunk($del_goods_ids,100);
                foreach ($page_goods_ids as $v){
                    GoodsGroupList::instance()
                        ->whereIn('goods_id',$v)
                        ->update(['df'=>1]);
                }
            }

            $normal_goods_group = $goods_df_group[0] ?? [];
            $goods_ids = [];//分类下未删除的商品
            foreach ($normal_goods_group as $v){
                if(in_array($v['class_id'],$class_ids)){
                    $goods_ids[] = $v['id'];
                }
            }

            $goods_group_goods_ids = GoodsGroupList::instance()
                ->where(['goods_group_id'=>$val['id']])
                ->select(['id','goods_id','df'])
                ->get();//当前商品分组下已经添加的商品（包含已软删除的商品）
            if($goods_group_goods_ids){
                $goods_group_goods_ids = $goods_group_goods_ids->toArray();
            }

            /*商品分组里已删除和正常状态的所有商品*/
            $all_goods_group_goods_ids = array_column($goods_group_goods_ids,'goods_id');

            $goods_group_goods_map = getArrayGroupData($goods_group_goods_ids,'df');

            /*商品分组里已删除的商品*/
            $before_del_goods_list = $goods_group_goods_map[1] ?? [];
            $before_del_goods_list_map = array_column($before_del_goods_list,null,'goods_id');
            $before_del_goods_ids = array_column($before_del_goods_list,'goods_id');

            /*商品分组里正常状态的商品*/
            //$normal_goods_list = $goods_group_goods_map[0] ?? [];

            /*商品分组新增从未添加的商品*/
            $insert_goods = array_diff($goods_ids,$all_goods_group_goods_ids);//获取商品分组没有添加的商品
            $insertGoodsList = [];
            foreach ($insert_goods as $k=>$v){
                $insertGoodsList[$k]['sid']            = $sid;
                $insertGoodsList[$k]['cid']            = $cid;
                $insertGoodsList[$k]['goods_group_id'] = $val['id'];
                $insertGoodsList[$k]['goods_id']       = $v;
                $insertGoodsList[$k]['cd']             = time();
            }
            if(!empty($insertGoodsList)){
                GoodsGroupList::instance()->insert($insertGoodsList);
            }

            $new_goods_ids = array_merge($goods_ids,$insert_goods);
            /*商品分组恢复之前软删除现在正常的商品*/
            $update_goods = array_intersect($new_goods_ids,$before_del_goods_ids);//获取商品分组之前删除的，现在正常的商品

            $goods_group_ids = [];
            foreach ($update_goods as $k=>$v){
                if(isset($before_del_goods_list_map[$v])){
                    $goods_group_ids[] = $before_del_goods_list_map[$v]['id'];
                }
            }
            if(!empty($goods_group_ids)){
                GoodsGroupList::instance()
                    ->whereIn('id',$goods_group_ids)
                    ->update(['df'=>0]);
            }
        }
    }

    /**
     * 商品分组队列消费
     * @param array $data
     */
    public function goodsGroup(array $data = [] ){
        $sid     = $data['sid'];
        $cid     = $data['cid'];
        $skucode = $data['skucode'];
        $is_add  = $data['is_add'];

        /*只同步商品分类*/
        $goods_group_ids = GoodsGroup::instance()
            ->where(['sid'=>$sid,'cid'=>$cid,'is_sync_goods'=>1,'df'=>0])
            ->where('goods_range',3)
            ->select(['id','class_ids'])
            ->get();
        if(!$goods_group_ids){
            return Normal::returnCode(Normal::SUC,"没有需要同步的商品");
        }
        $goods_info = Goods::instance()
            ->where(['sid'=>$sid,'cid'=>$cid,'skucode'=>$skucode])
            ->first();
        if(!$goods_info){
            return Normal::returnCode(Normal::SUC,"商品不存在");
        }

        $insertGoodsList = [];
        foreach ($goods_group_ids as $k=>$v){
            if(!$v['class_ids']){
                continue;
            }
            $class_ids = explode(',',$v['class_ids']);
            $class_children_ids = GoodsClass::instance()
                ->where(['sid'=>$sid,'cid'=>$cid,'df'=>0])
                ->whereIn('pid',$class_ids)
                ->pluck('id')->toArray();
            $all_class = array_unique(array_merge($class_ids,$class_children_ids));
            if($is_add == 1){
                if(in_array($goods_info['class_id'],$all_class) && $goods_info['df'] == 0){
                    $insertGoodsList[$k]['sid']            = $sid;
                    $insertGoodsList[$k]['cid']            = $cid;
                    $insertGoodsList[$k]['goods_group_id'] = $v['id'];
                    $insertGoodsList[$k]['goods_id']       = $goods_info['id'];
                    $insertGoodsList[$k]['cd']             = time();
                }
            }else{
                GoodsGroupList::instance()
                    ->where([
                        'sid'=>$sid,
                        'cid'=>$cid,
                        'goods_group_id'=>$v['id'],
                        'goods_id'=>$goods_info['id']
                    ])
                    ->update(['df'=>$goods_info['df']]);
            }
        }
        if($insertGoodsList){
            GoodsGroupList::instance()
                ->insert($insertGoodsList);
        }
        return Normal::returnCode(Normal::SUC,'成功');

    }

    /**
     * 商品变动-需要变更商品分组
     * @param array $msg
     */
    public function goodsGroupMessageProducer(array $data)
    {
        try {
            $message = new GoodsGroupProducer($data);
            $producer = ApplicationContext::getContainer()->get(Producer::class);
            $result = $producer->produce($message,true);
            if($result) {
                return Normal::returnCode(Normal::SUC,"发布成功");
            }
            return Normal::returnCode(Normal::FAIL,"发布消息队列失败");
        } catch ( \Throwable $th ) {
            return Normal::returnCode(Normal::FAIL,"发布消息队列失败【{$th->getMessage()}】");
        }
    }

    /**
     * 商品授权结束，下架本次商品没有授权的商品
     */
    public function downBatchGoods($cid)
    {
        $list=Goods::instance()->lists(['cid'=>$cid,'sync_off'=>1,'_fields_'=>'id']);
        if(empty($list)){
            return Normal::returnCode(Normal::SUC,"发布成功");
        }

        $newList = array_chunk($list, 10000);
        foreach ($newList as $list)
        {
            $goods_ids=array_column($list,'id');
            (new EsPublishMsgService())->pushNew($goods_ids,'channel','delete');
            MnStoreGoods::instance()->whereIn('goods_id',$goods_ids)->update(['df'=>1,'md'=>time()]);
            $storeGoodsList = MnStoreGoods::instance()->lists(['goods_id'=>$goods_ids,'num'=>0,'_fields_'=>'id']);
            $store_rows_ids = array_column($storeGoodsList,'id');
            if( $store_rows_ids ) {
                (new EsPublishMsgService())->pushNew($store_rows_ids,'store','delete');
            }
        }
        Goods::instance()->where('cid',$cid)->where('is_trade',0)->where('sync_off',1)->update([
            'df'  => 1,
            'sync_off'  => 0,
            'md' =>time()
        ]);
        return Normal::returnCode(Normal::SUC,"发布成功");
    }

}